
import Config from 'config';
import { toEncrypt, randomString } from 'stringEncrypt';
let app = getApp();
function HttpRequest(loading, url, sessionChoose, params, method, callBack, reject) {
  let token = app.getStorageByKey("token");
  let requestUrl = Config.api.baseUrl;
  //判断ukey是否存在
  // 存在就继续执行
  if (!!token) {
    if (loading == true) {
      wx.showLoading();
    }
    let paramSession = sessionChoose == 1 ? {
      'content-type': 'application/x-www-form-urlencoded'
    } : {
        'content-type': 'application/json'
      };
    var params = Object.prototype.toString.call(params) == "[object Object]" ? params : {};
    params["token"] = token;

    /**
     params["version"] = Config.version;
     params["nonce_str"] = randomString();
     params["vipcard_id"] = Config.vipcard_id;
     let serectParams = {
        ...params,
        sign: toEncrypt(params)
      }
     * */



    params["callback"] = url;

    if (Config.api.baseUrl.indexOf("wnworld") != -1) {
      requestUrl = Config.api.baseUrl + url;
    }
    wx.request({
      url: requestUrl,
      data: params,
      dataType: "json",
      header: paramSession,
      method: method,
      success: function (res) {
        if (loading == true) {
          wx.hideLoading(); //隐藏提示框
        }
        console.log("HttpRequest-success-xxxxxxxxxxxxxxxxxxxxxxxxxx")
       
        //token 存在 还返回408，这个时候就要强制
        if (res.data.code == 408) {
          asyncLogin(true).then((res) => {
            console.log("asyncLogin().then-success")
            HttpRequest(loading, url, sessionChoose, params, method, callBack, reject)
          })
        } else if (res.data.code == 400){
          wx.showToast({
            title: res.data.msg.toString(),
            icon: '',
            duration: 2000
          })
        }else {
          callBack(res.data);
        }
      },
      fail: function (res) {
        console.warn("HttpRequst当中wx.request fail 执行了：调用失败")
      }
    })
  } else {
    //不存在(或者) 重走登录流程
    //第一个执行的时候  后面的都需要挂起来
    asyncLogin(true).then((res) => {
      console.log("asyncLogin().then-没有token")
      HttpRequest(loading, url, sessionChoose, params, method, callBack, reject)
    })
  }
}
function asyncLogin(flag) {
  app.initNum++;
  return new Promise((reslove, reject) => {
    if (app.globalData.loginRuning) {
      //已经在执行了
      app.globalData.loginCollect.push(reslove);
    } else {
      app.globalData.loginRuning = true;
      work(reslove, reject, flag)
    }
    console.log(app.initNum)
  })
}


function _resloveRun() {
  app.globalData.loginCollect.forEach((reslove) => {
    reslove();
    console.log("app.globalData.loginCollect.forEach")
  });
  console.log("_resloveRun")
  app.globalData.loginRuning = false;
  app.globalData.loginCollect = [];
}


function work(reslove, reject, flag) {
  return new Promise(function () {
    if (flag) {
      wxLogin(reslove);
    } else {
      wx.checkSession({
        success: function () {
          console.group("checkSession-success");
          console.log("sessionKey未过期");
          //同步获取token
          let token = app.getStorageByKey("token");
          console.log("asyncLogin:" + token)
          //为了安全验证 判断ukey是否有本地存储
          if (!!token) {
            reslove();
            _resloveRun();
          } else {
            //重新走登录流程
            wxLogin(reslove);
          }
        },
        fail: function () {
          //重新走登录流程
          wxLogin(reslove);
        }
      })
    }

  })
}
function wxLogin(reslove) {
  wx.login({
    success(res) {
      console.log(res.code)
      if (res.code) {
        wx.request({
          url: "https://wnworld.com/CheYiBao/loginShouQuan.php",
          data: { code: res.code },
          dataType: "json",
          header: { 'content-type': 'application/x-www-form-urlencoded' },
          method: "POST",
          success: function (res) {
            console.log(res.data.data.token)

            if (res.data.code == 200) {
              app.globalData.token = res.data.data.token;
              app.setStorage("token", res.data.data.token)
              reslove();
              _resloveRun();
            }
          },
          fail: function (res) {
            console.warn("wxLogin当中wx.request fail 执行了：调用失败")
          }
        })
      } else {
        console.warn('登录失败！' + res.errMsg)
      }
    },
    fail: function () {
      console.warn("调用wx.login接口失败！")
    }
  })
}

app.asyncLogin = asyncLogin;



export { HttpRequest, asyncLogin, app }






